package ks.client.designfactory;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;

import ks.client.gamefactory.GameWindow;
import ks.client.gui.GMGUI;
import ks.common.games.Solitaire;
import ks.launcher.Main;

/**
 * How to launch a game from a Plugin given just the JAR file
 * 
 * @author George Heineman
 *
 */
public class SamplePluginLauncher {

	public static void main(String[] args) {
		File f = new File ("PLUGINS/Narcotic.jar"); 
		if (!f.exists()) {
			System.out.println("Can't find the Plugin");
			return;
		}
		
		// grab the PLUGIN entry from within its JAR file
		String mainName = null;
			try {
				JarInputStream jis = new JarInputStream(new FileInputStream(f));
				Manifest m = jis.getManifest();
				Attributes att = m.getMainAttributes();
				mainName  = att.getValue("Main-Class");
				System.out.println("Solitaire name is:" + mainName);
				jis.close();
			
			// Note that this URL could be REMOTE (http://) or LOCAL (file://)
			//
			URL pluginRootURL[] = new URL[1];
			pluginRootURL[0] = f.toURI().toURL(); 
			URLClassLoader urlClassLoader = new URLClassLoader(pluginRootURL);
			
//			pluginRootUrl = pluginRootUrl + varType + ".jar";
//			URL[] urls = new URL[1];
//			try {
//				urls[0] = new URL(pluginRootUrl);
//			} catch (MalformedURLException mue) {
//				System.err.println("Unable to access " + pluginRootUrl + " as a URL.");
//				EndGame.endGame(gmgui); // HEINEMAN
//				return false;
//			}
//			
			Class solName = urlClassLoader.loadClass(mainName);
			Solitaire solitaireVariation = (Solitaire) solName.newInstance();
			
			//GMGUI gui = lobby.getGMGUI();
			GameWindow gw = Main.generateWindow(solitaireVariation, 117);
			gw.setVisible(true);
			
			
		} catch (FileNotFoundException e) {
			System.out.println("Can't find the Plugin file: " + f);
			return;
		} catch (IOException e) {
			System.out.println("Problems while accessing " + f + "(" + e.getMessage() + ")");
			return;
		} catch (ClassNotFoundException e) {
			System.out.println("Plugin variation is not properly configured. Can't find main class:" + mainName);
			return;
		} catch (InstantiationException e) {
			System.out.println("Unable to properly instantiate Plugin " + mainName);
			return;
		} catch (IllegalAccessException e) {
			System.out.println("Encountered security exception with " + mainName);
			return;
		}
		
		// 
	}
}
